from machine import Pin
import utime
import lc
from machine import RTC
from machine import Pin, I2C,ADC
import PFC8563
import machine

pot = ADC(Pin(lc.voltagePin))
pot.atten(ADC.ATTN_6DB) 
pin1 = Pin(lc.led1, Pin.OUT,value=lc.ledoff)
ps=Pin(lc.voltageSwitch, Pin.OUT)

i2c = I2C(0,scl=Pin(lc.scl), sda=Pin(lc.sda),freq=400000)
PFC8563.i2c=i2c
rtc = machine.RTC()
rzk=rtc.memory()
def tp(str):
    print8(str+"     ",0,5)
def setaddress(x,y):
    x=x+4
    buf =b"\x00\x38" + bytes([64+y,0xe0+(x&0x0f),0xf0+((x&0xf0)>>4)])
    i2c.writeto(63,buf)
def write(buf):
    i2c.writeto(63,b"\x40"+buf)
def print8(str,x=0,y=0):
    setaddress(x,y)
    for i in str:
        write(rzk[640+(ord(i)-32)*5:640+(ord(i)-32)*5+5]+b'\x00')
def st1(t=0,r=0):
    str="%.2fC  %.2f%%    "%(t,r)
    for n in range(2):
        setaddress(0,n+6)
        for i in str:
            if ord(i)>=48 and ord(i)<=57:
                offset=1115+(ord(i)-48)*16+n*8
            if ord(i)== 45 :
                offset=1115+10*16+n*8  #-
            if ord(i) == 46:
                offset=1115+11*16+n*8  #.
            if ord(i) == 67:
                offset=1115+14*16+n*8  #C
            if ord(i) == 86:
                offset=1115+12*16+n*8  #V
            if ord(i) == 37:
                offset=1115+13*16+n*8 #%
            if ord(i) == 32:
                offset=1115+15*16+n*8 #%
            write(rzk[offset:offset+7])
def sht31m(i2c):
    i2c.writeto(68,b"\x2c\x06")
def sht31r(i2c):
    raw=i2c.readfrom(68,6)
    (t,h)=(raw[0] << 8) + raw[1], (raw[3] << 8) + raw[4]
    temp = -45 + (175 * (t / 65535))
    return temp, 100 * (h / 65535)
def getPFC8563(n):
    da=i2c.readfrom_mem(81,2,n)
    d=[]
    for i in da:
        d.append(((i>>4) * 10) + (i&0x0f))
    return d
def showtimehm(u):

    d=getPFC8563(7)
    if(d[2]==0 and d[4]==6 and u>3.5):
        PFC8563.sync(tp)
        d=getPFC8563(7)
        tp(f"{d[5]:02d}-{d[3]:02d} {d[2]:02d}:{d[1]:02d}")
    printN32_2(d[2],0)
    print8(f"20{d[6]:02d}-{d[5]:02d}-{d[3]:02d}",0,4)
    o=1371+d[4]*32
    setaddress(110,0)
    write(rzk[o:o+15])
    setaddress(110,1)
    write(rzk[o+16:o+31])
def printN32_2(n,x):
    for i in range(4):
        setaddress(x,i)
        oh=int(n/10)*64
        ol=int(n%10)*64
        write(rzk[oh+i*16:oh+i*16+15])
        write(rzk[ol+i*16:ol+i*16+15])
def deepwake():
    rtc=machine.RTC()
    print("deepwake")
    s=OneMinuteShow()
    machine.deepsleep((60-s)*1000)
#     machine.deepsleep(3000)

def OneMinuteShow():
    ps.on()
    sht31m(i2c)
    utime.sleep_ms(5)
    U_=[]
    for i in range(20):
        U_.append(pot.read())
    ps.off()
    d=getPFC8563(2)
    printN32_2(d[1],45)
    u=lc.getvolt(U_)
    print8("%.2fV   "%(u),80,4)
    machine.lightsleep(20)
    (t,h)=sht31r(i2c)
    st1(t,h)
    if(d[1]==0):showtimehm(u)
    return d[0]